<template>
    <div class="login-container">
        <el-form :model="form" :rules="rules" ref="loginFormRef" class="login-form" label-width="80px">

            <h2 class="login-title">登录</h2>

            <el-form-item label="用户名" prop="username">
                <el-input v-model="form.name" placeholder="请输入用户名" />
            </el-form-item>

            <el-form-item label="密码" prop="password">
                <el-input v-model="form.pwd" type="password" placeholder="请输入密码" show-password />
            </el-form-item>

            <el-form-item label="验证码" prop="captchaInput">
                <el-row :gutter="10" align="middle">
                    <el-col :span="14">
                        <el-input v-model="form.captchaInput" placeholder="请输入验证码" maxlength="4" />
                    </el-col>
                    <el-col :span="10">
                        <div class="captcha-img" @click="refreshCaptcha">{{ captcha }}</div>
                    </el-col>
                </el-row>
            </el-form-item>

            <el-form-item>
                <el-checkbox v-model="form.remember">记住密码</el-checkbox>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit" style="width: 100%">登录</el-button>
            </el-form-item>

        </el-form>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive ,onMounted} from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { useCounterStore } from '@/stores/counter'

const store=useCounterStore();
const router = useRouter()

const loginFormRef = ref()
const form = reactive({
    name: '',
    pwd: '',
    captchaInput: '',
    remember: false,
})

// 记住密码：页面加载时自动填充
const savedLogin = localStorage.getItem('loginInfo')
if (savedLogin) {
    try {
        const { name, pwd } = JSON.parse(savedLogin)
        form.name = name || ''
        form.pwd = pwd || ''
        form.remember = true
    } catch (e) {
        // ignore parse error
    }
}

const rules = {
    name: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    pwd: [{ required: true, message: '请输入密码', trigger: 'blur' }],
    captchaInput: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { min: 4, max: 4, message: '验证码为4位', trigger: 'blur' }
    ],
}

// 生成四位伪随机验证码
function generateCaptcha() {
    return Math.random().toString(36).slice(2, 6).toUpperCase()
}
const captcha = ref(generateCaptcha())
function refreshCaptcha() {
    captcha.value = generateCaptcha()
}

// 新增：封装登录请求
async function loginRequest(name: string, pwd: string) {
    // 你可以根据实际后端接口调整参数和请求方式
    return axios.post('http://localhost:8080/api/app/login/login', null, {
        params: { name, pwd }
    })
}

async function onSubmit() {
    loginFormRef.value.validate(async (valid: boolean) => {
        if (!valid) {
            ElMessage.error('请填写完整信息')
            return
        }
        if (form.captchaInput.toUpperCase() !== captcha.value) {
            ElMessage.error('验证码错误')
            refreshCaptcha()
            form.captchaInput = ''
            return
        }
        try {
            const res = await loginRequest(form.name, form.pwd)
            if (res.data.code == 200) {
                ElMessage.success('登录成功')
                // 登录成功后的逻辑
                store.RoleName=res.data.data.roleName
                store.UserName=res.data.data.userName
                // 记住密码逻辑
                if (form.remember) {
                    localStorage.setItem('loginInfo', JSON.stringify({ name: form.name, pwd: form.pwd }))
                } else {
                    localStorage.removeItem('loginInfo')
                }
                router.push('/main')
            } else {
                ElMessage.error('登录失败')
            }
        } catch (e) {
            ElMessage.error('请求失败')
        }
    })
}
</script>

<style scoped>
.login-container {
    min-height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background: url('https://images.unsplash.com/photo-1506744038136-46273834b3fb?auto=format&fit=crop&w=1500&q=80') no-repeat center center;
    background-size: cover;
}

.login-form {
    background: #fff;
    padding: 32px 28px 18px 28px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    width: 350px;
}

.login-title {
    text-align: center;
    margin-bottom: 18px;
}

.captcha-img {
    width: 90px;
    height: 32px;
    background: #f0f0f0;
    color: #333;
    font-size: 20px;
    letter-spacing: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
    border: 1px solid #eee;
    cursor: pointer;
    user-select: none;
}
</style>
